package top.yoahh.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import top.yoahh.system.entity.SysRole;
import top.yoahh.system.mapper.SysRoleMapper;

import java.util.Collection;
import java.util.List;

/**
 * 自定义FilterInvocationSecurityMetadataSource
 */
@Slf4j
@Component
public class FilterInvocationSecurityMetadataSourceConfig implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        log.info("进入自定义FilterInvocationSecurityMetadataSource");

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String url = ((FilterInvocation) o).getRequestUrl();
        log.info("请求的地址：{}", url);
        // 根据url去获取对应的角色
        List<SysRole> roleList = sysRoleMapper.queryByMenuUrl(url);
        if (roleList.size() == 0) {
            return SecurityConfig.createList("ROLE_LOGIN");
        }
        String[] roleArr = new String[roleList.size()];
        for (int i = 0; i < roleArr.length; i++) {
            roleArr[i] = roleList.get(i).getCode();
        }
        return SecurityConfig.createList(roleArr);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    /**
     * 是否支持校验
     *
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
